package org.btik.video.server.push;

import org.btik.app.tool.AsyncTaskExecutor;
import org.btik.video.server.iface.VideoChannel;
import org.btik.video.server.push.udp.RawUdpVideoChannel;
import org.btik.video.server.push.web.MJPEGVideoChannel;
import org.btik.video.server.push.web.SoSendTimeoutTicker;

import java.util.concurrent.ConcurrentHashMap;


/**
 * @author lustre
 * @since 2023/4/27 9:52
 */
public class VideoChannelFactory {
    private final ConcurrentHashMap<String, MJPEGVideoChannel> mjpegVideoChannelMap = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<String, RawUdpVideoChannel> videoChannelMap = new ConcurrentHashMap<>();

    private AsyncTaskExecutor asyncTaskExecutor;

    private SoSendTimeoutTicker soSendTimeoutTicker;

    public void setAsyncTaskExecutor(AsyncTaskExecutor asyncTaskExecutor) {
        this.asyncTaskExecutor = asyncTaskExecutor;
    }

    public void setSoSendTimeoutTicker(SoSendTimeoutTicker soSendTimeoutTicker) {
        this.soSendTimeoutTicker = soSendTimeoutTicker;
    }

    public MJPEGVideoChannel getMJPEGVideoChannel(String sn) {
        return mjpegVideoChannelMap.get(sn);
    }

    public RawUdpVideoChannel getRawUdpVideoChannel(String sn) {
        return videoChannelMap.get(sn);
    }

    public MJPEGVideoChannel createMJPEGVideoChannel(int channelIndex, String sn) {
        MJPEGVideoChannel videoChannel = mjpegVideoChannelMap.computeIfAbsent(sn,
                channelIdStr -> new MJPEGVideoChannel(channelIdStr, asyncTaskExecutor));
        soSendTimeoutTicker.registerChannel(channelIndex, videoChannel);
        return videoChannel;
    }

    public VideoChannel createRawUDPVideoChannel(int channelIndex, String sn) {
        soSendTimeoutTicker.deregisterChannel(channelIndex);
        return videoChannelMap.computeIfAbsent(sn, RawUdpVideoChannel::new);
    }
}
